package be.kuleuven.peno3.mobiletoledo.Data.Client;

import java.io.IOException;
import java.util.Calendar;

import org.apache.commons.httpclient.HttpException;
import org.json.JSONException;
import org.json.JSONObject;

import be.kuleuven.peno3.mobiletoledo.model.Message;

import com.google.gson.Gson;

public abstract class MessagesClient extends Client{
	
	public  static Message[] getMessages(int course){
		try {
			String url = "course_id="+course;
			url = host+"/MessageHandler/getMessages?"+encode(url);
			String json = stringOfUrl(url);
			
			Message[] messages =new Gson().fromJson(json, Message[].class);
			
			return messages;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return null;
		} catch (HttpException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public  static Message getMessage(int messageId){
		try {
			String json = stringOfUrl(host+"/MessageHandler/getMessage?message_id="+messageId);
			
			Message[] messages =new Gson().fromJson(json, Message[].class);
			
			return messages[0];
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return null;
		} catch (HttpException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static boolean addMessage(String title, String body, String author, int courseId, Calendar cal) {
		try {
			String url="title="+title+"&body="+body+"&author="+author+"&course_id="+courseId+"&cal="+toSQLString(cal);
			url=encode(url);
			url=host+"/MessageHandler/addMessage?"+url;
			String json = stringOfUrl(url);
			
			String result = null;
			try {
				result = (String) new JSONObject(json).get("result");
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			}
			
			if(result.indexOf("successful")>0) {
				return true;
			}
			return false;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
